﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ChuanYe.Models;
using ChuanYe.IDAL;
using ChuanYe.Models.Model;
using ChuanYe.Utils;
using EntityFramework.Extensions;
using System.Data.Entity;

namespace ChuanYe.DAL
{
    public class UsersInfosDAL : IUsersInfosDAL
    {
        #region 登录
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public LoginUserModel LoginIn(UsersInfos model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var linq = db.UsersInfos
                    .GroupJoin(
                    db.RolePower,
                    A => A.RoleID,
                    B => B.R_ID,
                    (A, B) => new LoginUserModel
                    {
                        ID = A.ID,
                        PassWord = A.PassWord,
                        Personal = A.Personal,
                        PositionID = A.PositionID,
                        RoleID = A.RoleID,
                        UserCode = A.UserCode,
                        UserName = A.UserName,
                        DepID = A.Section,
                        DepName = null,
                        RoleName = null,
                        Address = null,
                    }
                    )
                    .GroupJoin(
                    db.Departments,
                    C => C.DepID,
                    D => D.ID,
                    (C, D) => new LoginUserModel
                    {
                        ID = C.ID,
                        PassWord = C.PassWord,
                        Personal = C.Personal,
                        PositionID = C.PositionID,
                        RoleID = C.RoleID,
                        UserCode = C.UserCode,
                        UserName = C.UserName,
                        DepID = C.DepID,
                        DepName = D.FirstOrDefault(x => x.ID == C.DepID).DepName,
                        RoleName = null,
                        Address= D.FirstOrDefault(x => x.ID == C.DepID).Address
                    }
                    )
                    .GroupJoin(
                    db.MemberShip_Roles,
                    E => E.RoleID,
                    F => F.ID,
                    (E, F) => new LoginUserModel
                    {
                        ID = E.ID,
                        PassWord = E.PassWord,
                        Personal = E.Personal,
                        PositionID = E.PositionID,
                        RoleID = E.RoleID,
                        UserCode = E.UserCode,
                        UserName = E.UserName,
                        DepID = E.DepID,
                        DepName = E.DepName,
                        RoleName = F.FirstOrDefault(x => x.ID == E.RoleID).RoleName,
                        Address=E.Address
                    }
                    );
                LoginUserModel result = linq.FirstOrDefault(m => m.PassWord == model.PassWord && m.UserCode == model.UserCode );
                if (result != null&& result!= new LoginUserModel())
                {
                    BrowsingTotal rt = db.BrowsingTotal.FirstOrDefault();
                    if (rt == null|| rt == new BrowsingTotal())
                    {
                        BrowsingTotal btModel = new BrowsingTotal();
                        btModel.Total = 1;
                        db.BrowsingTotal.Add(btModel);
                        db.SaveChanges();
                    }
                    else
                    {
                        rt.Total = rt.Total + 1;
                        db.SaveChanges();
                    }
                }
                if (result == null)
                {
                    result = new LoginUserModel();
                }
                List<PowerModel> PowerList = db.Power
                    .Join(
                    db.RolePower,
                    A => A.Power_ID,
                    B => B.P_ID,
                    (A, B) => new PowerModel
                    {
                        ID = A.ID,
                        Power_ID = A.Power_ID,
                        Power_Name = A.Power_Name,
                        ShowName = A.ShowName,
                        Fid = A.Fid,
                        Path = A.Path,
                        Sort = A.Sort,
                        RoleID = B.R_ID
                    }
                    )
                    .Where(M => M.RoleID == result.RoleID)
                    .ToList();
                List<PowerModel> PowerListResult = new List<PowerModel>();
                List<PowerModel> PowerListRst = GetPowerModelList(PowerList, PowerListResult, "0");
                result.Powers = PowerListRst;
                return result;
            }
        }

        /// <summary>
        ///  重构登录方法 2018-06-26 解决登录速度过慢
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public LoginUserModel Login(string userCode)
        {
            LoginUserModel result = null;
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                result =db.View_UserInfos_Departments_MemberShipRoles.Where(p => p.UserCode == userCode)
                    .Select(s=>new LoginUserModel {
                        ID = s.ID,
                        PassWord = s.PassWord,
                        Personal = s.Personal,
                        PositionID = s.PositionID,
                        RoleID = s.RoleID,
                        UserCode = s.UserCode,
                        UserName = s.UserName,
                        DepID = s.Section,
                        DepName = s.DepName,
                        RoleName = s.RoleName,
                        Address =s.Address,
                        IsDisable=s.IsDisable,
                        Division=s.Division,
                        IsManager=s.IsManager==null?false:s.IsManager.Value,
                    }).FirstOrDefault();
            }
            return result;
        }

        /// <summary>
        /// 根据权限ID 获取所有子级权限
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public List<PowerModel> GetPower(int roleID)
        {
            List<PowerModel> result = null;
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                List<PowerModel> PowerList = db.Power
                  .Join(
                  db.RolePower,
                  A => A.Power_ID,
                  B => B.P_ID,
                  (A, B) => new PowerModel
                  {
                      ID = A.ID,
                      Power_ID = A.Power_ID,
                      Power_Name = A.Power_Name,
                      ShowName = A.ShowName,
                      Fid = A.Fid,
                      Path = A.Path,
                      Sort = A.Sort,
                      RoleID = B.R_ID
                  }).Where(M => M.RoleID == roleID).ToList();
                result = GetPowerModelList(PowerList, new List<PowerModel>(), "0");
            }
            return result;
        }


        public List<PowerModel> GetPowerModelList(List<PowerModel> PowerList, List<PowerModel> PowerResult, string Fid)
        {
            if (PowerResult.Count == 0)
            {
                PowerResult = PowerList.Where(m => m.Fid == "0").ToList();
            }
            foreach (PowerModel model in PowerResult)
            {
                model.ChildPowerList = PowerList.Where(m => m.Fid == model.Power_ID).ToList();
                if (model.ChildPowerList.Count != 0)
                {
                    GetPowerModelList(PowerList, model.ChildPowerList, model.Power_ID);
                }
            }
            return PowerResult;
        }

        /// <summary>
        /// 登录有户信息
        /// </summary>
        /// <returns></returns>
        public LoginUserModel LoginUserInfos(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.UsersInfos
                    .GroupJoin(
                    db.RolePower,
                    A => A.RoleID,
                    B => B.R_ID,
                    (A, B) => new LoginUserModel
                    {
                        ID = A.ID,
                        PassWord = A.PassWord,
                        Personal = A.Personal,
                        PositionID = A.PositionID,
                        RoleID = A.RoleID,
                        UserCode = A.UserCode,
                        UserName = A.UserName,
                        DepID = A.Section,
                        DepName = null,
                        RoleName = null
                    }
                    )
                    .GroupJoin(
                    db.Departments,
                    C => C.DepID,
                    D => D.ID,
                    (C, D) => new LoginUserModel
                    {
                        ID = C.ID,
                        PassWord = C.PassWord,
                        Personal = C.Personal,
                        PositionID = C.PositionID,
                        RoleID = C.RoleID,
                        UserCode = C.UserCode,
                        UserName = C.UserName,
                        DepID = C.DepID,
                        DepName = D.FirstOrDefault(x => x.ID == C.DepID).DepName,
                        RoleName = null
                    }
                    )
                    .GroupJoin(
                    db.MemberShip_Roles,
                    E => E.RoleID,
                    F => F.ID,
                    (E, F) => new LoginUserModel
                    {
                        ID = E.ID,
                        PassWord = E.PassWord,
                        Personal = E.Personal,
                        PositionID = E.PositionID,
                        RoleID = E.RoleID,
                        UserCode = E.UserCode,
                        UserName = E.UserName,
                        DepID = E.DepID,
                        DepName = E.DepName,
                        RoleName = F.FirstOrDefault(x => x.ID == E.RoleID).RoleName
                    }
                    )
                    .FirstOrDefault(m => m.ID == ID);
            }
        }

        /// <summary>
        /// 根据ID判断是否存在
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public bool IsIDRight(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                UsersInfos model = db.UsersInfos.FirstOrDefault(m => m.ID == ID);
                return model == null ? false : true;
            }
        }
        #endregion

        #region 模块管理
        /// <summary>
        /// 添加模块
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int PowerCreate(Power model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                db.Power.Add(model);
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 删除模块
        /// </summary>
        /// <param name="ID">模块ID</param>
        /// <returns></returns>
        public int PowerDelete(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.Power.FirstOrDefault(m => m.ID == ID);
                if (Info != null)
                {
                    db.Power.Remove(Info);
                }
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 模块详情
        /// </summary>
        /// <param name="ID">模块ID</param>
        /// <returns></returns>
        public Power PowerInfo(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.Power.FirstOrDefault(m => m.ID == ID);
            }
        }
        /// <summary>
        /// 修改模块
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int PowerUpdate(Power model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.Power.FirstOrDefault(m => m.ID == model.ID);
                if (Info != null)
                {
                    Info.Fid = model.Fid;
                    Info.Path = model.Path;
                    Info.Power_ID = model.Power_ID;
                    Info.Power_Name = model.Power_Name;
                    Info.ShowName = model.ShowName;
                    Info.Sort = model.Sort;
                }
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 查询模块
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public PowerResult PowerGetList(PowerSearch Search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return new PowerResult();
            }
        }
        /// <summary>
        /// 查询全部模块
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<Power> PowerGetAll(PowerSearch Search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.Power.ToList();
            }
        }
        #endregion

        #region 职务管理
        /// <summary>
        /// 是否已有相同的职务名称
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int PositionIsHave(string PositionName)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                List<Position> result = db.Position.Where(m => m.PositionName == PositionName).ToList();
                return result.Count();
            }
        }

        public int PositionIsHave(string positionName,int id=0)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {

                var where = PredicateExtensionses.True<Position>();
                where = where.And(m => m.PositionName == positionName);
                if (id != 0)
                {
                    where = where.And(m => m.ID != id);
                }
                List<Position> result = db.Position.Where(where).ToList();
                return result.Count();
            }
        }



        /// <summary>
        /// 添加职务
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int PositionCreate(Position model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                db.Position.Add(model);
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 删除职务
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public int PositionDelete(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.Position.FirstOrDefault(m => m.ID == ID);
                if (Info != null)
                {
                    db.Position.Remove(Info);
                }
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 职务详情
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public Position PositionInfo(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.Position.FirstOrDefault(m => m.ID == ID);
            }
        }
        /// <summary>
        /// 修改职务
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int PositionUpdate(Position model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.Position.FirstOrDefault(m => m.ID == model.ID);
                if (Info != null)
                {
                    Info.PositionName = model.PositionName;
                    Info.Sort = model.Sort;
                }
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 获取全部职务
        /// </summary>
        /// <returns></returns>
        public List<Position> PositionGetAll()
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.Position.ToList();
            }
        }

        /// <summary>
        /// 获取职务分页
        /// </summary>
        /// <returns></returns>
        public List<Position> PositionByPage(string positionName, GridPager pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var where = PredicateExtensionses.True<Position>();
                if (!string.IsNullOrEmpty(positionName))
                {
                    where = where.And(p => p.PositionName.Contains(positionName));
                }

           
                var result = db.Position.Where(where)
                       .OrderByDescending(o => o.ID)
                       .Skip(pager.rows * (pager.page - 1))
                       .Take(pager.rows)
                       .ToList();
                pager.totalRows = db.Position.Where(where).Count();
                return result;
            }
        }

        #endregion

        #region 角色管理
        /// <summary>
        /// 获取权限树
        /// </summary>
        /// <returns></returns>
        public List<PowerModel> PowerGetAllTree()
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                List<PowerModel> PowerList = db.Power.Select(m=>new PowerModel {
                     ID=m.ID,
                     Fid=m.Fid,
                     Power_ID=m.Power_ID,
                     Power_Name= m.Power_Name,
                     ShowName= m.ShowName,
                     Sort=m.Sort  
                }).ToList();
                List<PowerModel> PowerListResult = new List<PowerModel>();
                return GetPowerModelList(PowerList, PowerListResult, "0");
            }
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="model"></param>
        /// <param name="RolePowerList"></param>
        /// <returns></returns>
        public int RolesCreate(MemberShip_Roles model, List<RolePower> RolePowerList)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                db.MemberShip_Roles.Add(model);
                int RT = db.SaveChanges();
                foreach (RolePower RP in RolePowerList)
                {
                    RP.R_ID = model.ID;
                }
                db.RolePower.AddRange(RolePowerList);
                db.SaveChanges();
                return RT;
            }
        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public int RolesDelete(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.MemberShip_Roles.FirstOrDefault(m => m.ID == ID);
                if (Info != null)
                {
                    db.MemberShip_Roles.Remove(Info);
                }
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 角色详情
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public MemberShip_RolesResult RolesInfo(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                MemberShip_RolesResult result = new MemberShip_RolesResult();
                result.MemberShip_Role = db.MemberShip_Roles.FirstOrDefault(m => m.ID == ID);
                result.RolePowerList = db.RolePower.Where(m => m.R_ID == ID).ToList();
                return result;
            }
        }



        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="model"></param>
        /// <param name="RolePowerList"></param>
        /// <returns></returns>
        public int RolesUpdate(MemberShip_Roles model, List<RolePower> RolePowerList)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.MemberShip_Roles.FirstOrDefault(m => m.ID == model.ID);
                if (Info != null)
                {
                    Info.RoleName = model.RoleName;
                    Info.Description = model.Description;
                    Info.Enabled = model.Enabled;
                }
                var OldRolePower = db.RolePower.Where(m => m.R_ID == model.ID);
                db.RolePower.RemoveRange(OldRolePower);
                db.RolePower.AddRange(RolePowerList);
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 获取全部角色
        /// </summary>
        /// <returns></returns>
        public List<MemberShip_Roles> MemberShip_RolesGetAll()
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.MemberShip_Roles.ToList();
            }
        }
        /// <summary>
        /// 分页查询角色
        /// </summary>
        /// <param name="Pager"></param>
        /// <returns></returns>
        public MemberShip_RolesSearchResult MemberShip_RolesSearch(GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                MemberShip_RolesSearchResult result = new MemberShip_RolesSearchResult();
                result.RoleList= db.MemberShip_Roles
                     .OrderByDescending(m=>m.ID)
                     .Skip(Pager.rows * (Pager.page - 1))
                     .Take(Pager.rows)
                     .ToList();
                result.totalRows = db.MemberShip_Roles.Count();
                return result;
            }
        }
        #endregion

        #region 机构管理
        /// <summary>
        /// 添加机构
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int DepartmentsCreate(Departments model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                db.Departments.Add(model);
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 删除机构
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public int DepartmentsDelete(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.Departments.FirstOrDefault(m => m.ID == ID);
                if (Info != null)
                {
                    db.Departments.Remove(Info);
                }
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 机构详情
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public Departments DepartmentsInfo(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.Departments.FirstOrDefault(m => m.ID == ID);
            }
        }

        public List<Departments> DepartmentsInfo(string address)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                return db.Departments.Where(p => p.Address == address).OrderByDescending(o=>o.ID).ToList();
            }
        }


        /// <summary>
        /// 修改机构
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int DepartmentsUpdate(Departments model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.Departments.FirstOrDefault(m => m.ID == model.ID);
                if (Info != null)
                {
                    Info.DepName = model.DepName;
                    Info.Manager = model.Manager;
                    Info.ManagerCode = model.ManagerCode;
                    Info.DepTel = model.DepTel;
                    Info.Leader = model.Leader;
                    Info.LeaderTel = model.LeaderTel;
                    Info.IsSend = model.IsSend;
                    Info.Sort = model.Sort;
                    Info.Address = model.Address;
                    Info.FID = model.FID;
                }
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 机构查询
        /// </summary>
        /// <param name="Search"></param>
        /// <param name="Pager"></param>
        /// <returns></returns>
        public DepartmentsSearchResult DepartmentsSearch(DepartmentsSearch Search,GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var linq = db.Departments;
                DepartmentsSearchResult result = new DepartmentsSearchResult();
                result.DepartmentsList = linq
                       .OrderByDescending(M=>M.ID)
                       .Skip(Pager.rows * (Pager.page - 1))
                       .Take(Pager.rows)
                       .ToList();
                result.totalRows = linq.Count();
                return result;
            }
        }


        /// <summary>
        /// 获取部门下拉框
        /// </summary>
        /// <returns></returns>
        public List<DepartmentsAllModel> DepartmentsGetAll()
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                List<DepartmentsAllModel> DepartmentsAll = db.Departments
                    .Select(m => new DepartmentsAllModel
                    {
                        ID = m.ID,
                        FID = m.FID,
                        DepName = m.DepName,
                        Sort=m.Sort
                    }).OrderBy(s=>s.Sort).ToList();
                List<DepartmentsAllModel> PowerListResult = new List<DepartmentsAllModel>();
                List<DepartmentsAllModel> PowerListRst = GetDepartmentsList(DepartmentsAll, PowerListResult, 0);
                return PowerListRst;
            }
        }
        public List<DepartmentsAllModel> GetDepartmentsList(List<DepartmentsAllModel> DepartmentsList, List<DepartmentsAllModel> DepartmentsResult, int Fid)
        {
            if (DepartmentsResult.Count == 0)
            {
                DepartmentsResult = DepartmentsList.Where(m => m.FID == 0).ToList();
            }
            foreach (DepartmentsAllModel model in DepartmentsResult)
            {
                model.ChildList = DepartmentsList.Where(m => m.FID == model.ID).ToList();
                if (model.ChildList.Count != 0)
                {
                    GetDepartmentsList(DepartmentsList, model.ChildList, model.ID);
                }
            }
            return DepartmentsResult;
        }
        #endregion

        #region 用户管理
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UsersInfosCreate(UsersInfos model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                db.UsersInfos.Add(model);
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public int UsersInfosDelete(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.UsersInfos.FirstOrDefault(m => m.ID == ID);
                if (Info != null)
                {
                    db.UsersInfos.Remove(Info);
                }
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 用户详情
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public UsersInfos UsersInfosInfo(int ID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                UsersInfos result= db.UsersInfos.FirstOrDefault(m => m.ID == ID);
                result.PassWord = "";
                return result;
            }
        }
        /// <summary>
        /// 用户修改
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public int UsersInfosUpdate(UsersInfos model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info= db.UsersInfos.FirstOrDefault(m => m.ID == model.ID);
                if (Info != null)
                {
                    Info.IsManager = model.IsManager;
                    Info.IsSafeDelivery = model.IsSafeDelivery;
                    Info.Division = model.Division;
                    Info.IsOfficial = model.IsOfficial;
                    Info.IsFire = model.IsFire;
                    if (!string.IsNullOrEmpty(model.PassWord))
                    {
                        Info.PassWord = model.PassWord;
                    }
                    else
                    {
                        Info.PassWord = Info.PassWord;
                    }
                    Info.Personal = model.Personal;
                    Info.Phone = model.Phone;
                    Info.PositionID = model.PositionID;
                    Info.RoleID = model.RoleID;
                    Info.Section = model.Section;
                    Info.Sort = model.Sort;
                    Info.UserCode = model.UserCode;
                    Info.UserName = model.UserName;
                }
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 用户查询
        /// </summary>
        /// <param name="Search"></param>
        /// <param name="Pager"></param>
        /// <returns></returns>
        public UsersInfosSearchResult UsersInfosSelete(UsersInfosSearch Search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var where = PredicateExtensionses.True<UsersInfosSearchModel>();
                if (!string.IsNullOrEmpty(Search.UserName))
                {
                    where = where.And(p=>p.UserName.Contains(Search.UserName));
                }
                if (Search.Section > 0)
                {
                    where = where.And(p => p.Section==Search.Section);
                }
                if (Search.RoleID > 0)
                {
                    where = where.And(p => p.RoleID == Search.RoleID);
                }
                UsersInfosSearchResult result = new UsersInfosSearchResult();
                var linq = db.UsersInfos
                    .Join(
                    db.Departments,
                    A => A.Section,
                    B => B.ID,
                    (A, B) => new UsersInfosSearchModel
                    {
                        CreateTime = A.CreateTime,
                        UserCode = A.UserCode,
                        ID = A.ID,
                        UserName = A.UserName,
                        Section = A.Section,
                        DepName = B.DepName,
                        RoleID = A.RoleID,
                        RoleName = null,
                        Phone = A.Phone,
                        PositionID = A.PositionID,
                        PositionName = null,
                        Sort = A.Sort
                    }
                    )
                    .Join(db.Position,
                    C => C.PositionID,
                    D => D.ID,
                    (C, D) => new UsersInfosSearchModel
                    {
                        CreateTime = C.CreateTime,
                        UserCode = C.UserCode,
                        ID = C.ID,
                        UserName = C.UserName,
                        Section = C.Section,
                        DepName = C.DepName,
                        RoleID = C.RoleID,
                        RoleName = null,
                        Phone = C.Phone,
                        PositionID = C.PositionID,
                        PositionName = D.PositionName,
                        Sort = C.Sort
                    }
                    )
                    .Join(db.MemberShip_Roles,
                    E => E.RoleID,
                    F => F.ID,
                    (E, F) => new UsersInfosSearchModel
                    {
                        CreateTime = E.CreateTime,
                        UserCode = E.UserCode,
                        ID = E.ID,
                        UserName = E.UserName,
                        Section = E.Section,
                        DepName = E.DepName,
                        RoleID = E.RoleID,
                        RoleName = F.RoleName,
                        Phone = E.Phone,
                        PositionID = E.PositionID,
                        PositionName = E.PositionName,
                        Sort = E.Sort
                    }
                    )
                    .Where(where);
                result.UsersList= linq.OrderByDescending(m => m.CreateTime)
                    .Skip(Pager.rows * (Pager.page - 1))
                    .Take(Pager.rows)
                    .ToList();
                result.totalRows = linq.Count();
                return result;
            }
        }


        /// <summary>
        /// 用户查询
        /// </summary>
        /// <param name="Search"></param>
        /// <param name="Pager"></param>
        /// <returns></returns>
        public UsersInfosSearchResult UsersInfosSelete2(UsersInfosSearch Search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var where = PredicateExtensionses.True<View_UsersInfosSelete>();
                if (!string.IsNullOrEmpty(Search.UserName))
                {
                    where = where.And(p => p.UserName.Contains(Search.UserName));
                }
                if (Search.Section > 0)
                {
                    where = where.And(p => p.Section == Search.Section);
                }
                if (Search.RoleID > 0)
                {
                    where = where.And(p => p.RoleID == Search.RoleID);
                }
                if (!string.IsNullOrEmpty(Search.Phone))
                {
                    where = where.And(p => p.Phone == Search.Phone);
                }
                UsersInfosSearchResult result = new UsersInfosSearchResult();
                var  list= db.View_UsersInfosSelete.Where(where).OrderByDescending(o=>o.Division).ThenBy(t=>t.UserCode)
                    .Select(s => new UsersInfosSearchModel
                    {
                        CreateTime = s.CreateTime,
                        UserCode = s.UserCode,
                        ID = s.ID,
                        UserName = s.UserName,
                        Section = s.Section,
                        DepName = s.DepName,
                        RoleID = s.RoleID,
                        RoleName = s.RoleName,
                        Phone = s.Phone,
                        PositionID = s.PositionID,
                        PositionName = s.PositionName,
                        Sort = s.Sort,
                        IsDisable=s.IsDisable==null ? false:s.IsDisable
                    })
                .OrderByDescending(m => m.ID)
                .Skip(Pager.rows * (Pager.page - 1))
                .Take(Pager.rows)
                .ToList();
                result.UsersList = list;
                result.totalRows =db.View_UsersInfosSelete.Where(where).Count();
                return result;
            }
        }






        public List<UsersInfos> GetUserInfos(List<int> ids)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                List<UsersInfos> result = db.UsersInfos.Where(p=>ids.Contains(p.ID)).ToList();
                return result;
            }

        }


        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int ChangePW(UsersInfos model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var Info = db.UsersInfos.FirstOrDefault(m => m.ID == model.ID);
                if (Info != null)
                {
                    Info.PassWord = model.PassWord;
                }
                return db.SaveChanges();
            }
        }

        public int UsersInfosUpdateDisable(int userid,bool isDisable)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var where = PredicateExtensionses.True<UsersInfos>();
                where = where.And(p => p.ID == userid);
                return db.UsersInfos.Where(where).Update(u => new UsersInfos { IsDisable= isDisable });
            }
        }

        public UsersInfos UsersInfosInfo(string  userCode)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                UsersInfos result = db.UsersInfos.FirstOrDefault(m => m.UserCode == userCode);
                return result;
            }
        }

        public List<UsersInfos> UsersInfosByPhone(string phone)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var result = db.UsersInfos.Where(m => m.Phone == phone).ToList();
                return result;
            }
        }


        public List<UsersInfos> UsersInfosByUserCode(string userCode)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var result = db.UsersInfos.Where(m => m.UserCode == userCode).ToList();
                return result;
            }
        }

        public int UsersInfosCount(int positionID, bool isOfficial)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var result = db.UsersInfos.Where(m => m.PositionID == positionID && m.IsOfficial== isOfficial).Count();
                return result;
            }
        }

        #endregion

        #region 日志管理
        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int DocOperationLogCreate(DocOperationLog model)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                db.DocOperationLog.Add(model);
                return db.SaveChanges();
            }
        }
        /// <summary>
        /// 日志查询
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public DocOperationLogResult DocOperationLogSearch(DocOperationLogSearch Search, GridPager Pager)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                DocOperationLogResult result = new DocOperationLogResult();
                var linq = db.DocOperationLog
                    .OrderByDescending(m => m.indate)
                    .Where(m => (Search.stateTime == null || m.indate >= Search.stateTime) &&
                    (Search.endTime == null || m.indate <= Search.endTime)
                    );
                result.DocOperationLogList= linq
                    .Skip(Pager.rows * (Pager.page - 1))
                    .Take(Pager.rows)
                    .ToList();
                result.totalRows = linq.Count();
                return result;
            }
        }

        /// <summary>
        /// 更新浏览总人数
        /// </summary>
        /// <returns></returns>
        public void UpdateBrowsingTotal()
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var temp= db.BrowsingTotal.FirstOrDefault();
                if (temp != null)
                {
                    temp.Total = temp.Total + 1;
                    db.SaveChanges();
                }
            }
        }

        #endregion


        #region 安全登录秘钥

        public List<U_AppAuthor> GetAppAuthor(int appId)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                if (appId == 0)
                {
                    return db.U_AppAuthor.ToList();
                }
                else
                {
                    return db.U_AppAuthor.Where(p => p.AppId == appId).ToList();
                }
            }
        }
        #endregion


        #region 短信组管理

        public int AddOutsideUserInfos(U_OutsideUserInfos info)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                db.U_OutsideUserInfos.Add(info);
                return db.SaveChanges();
            }
        }

        public List<U_OutsideUserInfos> OutsideUserInfosSelect(OutsideUserInfoSearch Search, GridPager Pager, ref int totalRows)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var where = PredicateExtensionses.True<U_OutsideUserInfos>();
                if (!string.IsNullOrEmpty(Search.UserName))
                {
                    where = where.And(p => p.UserName.Contains(Search.UserName));
                }

                if (!string.IsNullOrEmpty(Search.UserPhone))
                {
                    where = where.And(p => p.UserPhone.Contains(Search.UserPhone));
                }
                var result = db.U_OutsideUserInfos.Where(where)
                       .OrderByDescending(o => o.Sort).ThenByDescending(o => o.DepName).ThenBy(o => o.ID)
                       .Skip(Pager.rows * (Pager.page - 1))
                       .Take(Pager.rows)
                       .ToList();

                totalRows = db.U_OutsideUserInfos.Where(where).Count();
                return result;
            }
        }


        public List<U_OutsideUserInfos> OutsideUserInfosSelect(int selectType)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var where = PredicateExtensionses.True<U_OutsideUserInfos>();
                if (selectType == 1)
                {
                    where = where.And(p => p.IsSafeSMS == true);
                }
                else if (selectType == 2)
                {
                    where = where.And(p => p.IsFireSMS == true);
                }
                else if(selectType==3)
                {
                    where = where.And(p => p.IsResponSMS == true);
                }
                //where = where.And(p => p.IsDisable==true);
                var result = db.U_OutsideUserInfos.Where(where).OrderByDescending(o=>o.Sort).ThenByDescending(o=>o.DepName).ThenBy(o=>o.ID).ToList();
                return result;
            }
        }


        public int OutsideUserInfosDelete(int id)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var where = PredicateExtensionses.True<U_OutsideUserInfos>();
                where = where.And(p=>p.ID==id);
                return db.U_OutsideUserInfos.Where(where).Delete();
            }
        }

        public int OutsideUserInfosUpdate(U_OutsideUserInfos info)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var where = PredicateExtensionses.True<U_OutsideUserInfos>();
                where = where.And(p => p.ID == info.ID);
                return db.U_OutsideUserInfos.Where(where)
                    .Update(u => 
                    new U_OutsideUserInfos {
                        UserName = info.UserName,UserPhone=info.UserPhone,
                        IsFireSMS =info.IsFireSMS,IsResponSMS=info.IsResponSMS,
                        IsSafeSMS =info.IsSafeSMS,CreateTime=info.CreateTime,
                        PositionID=info.PositionID,
                        PositionName=info.PositionName,
                        DepName=info.DepName,
                        Sort=info.Sort
                    });
            }
        }

        public U_OutsideUserInfos OutsideUserInfosDetail(int id)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var where = PredicateExtensionses.True<U_OutsideUserInfos>();
                where = where.And(p => p.ID == id);
                return db.U_OutsideUserInfos.Where(where).FirstOrDefault();
            }
        }



        public LoginUserCache GetLoginUserCache(int userID)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var info = db.LoginUserCache.Where(p => p.UserID == userID).FirstOrDefault();
                return info;
            }
        }

        public void AddOrUpdateLoginUserCache(LoginUserCache info)
        {
            using (SJZHPlatFormEntities db = new SJZHPlatFormEntities())
            {
                var exist = db.LoginUserCache.Where(p => p.UserID == info.UserID).FirstOrDefault();
                if (exist == null)
                { 
                    info.LoginUserCacheID = 0;
                    db.LoginUserCache.Add(info);
                    db.Entry<LoginUserCache>(info).State = EntityState.Added;
                    db.SaveChanges();
                }
                else
                {
                    exist.StartTime = info.StartTime;
                    exist.Value = info.Value == 0 ? exist.Value : info.Value;
                    exist.LoginUserModelJson = info.LoginUserModelJson;
                    db.LoginUserCache.Add(exist);
                    db.Entry<LoginUserCache>(exist).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }
        }

        #endregion
    }
}
